using EasyElasticLogger.NETFramework.ES.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace EasyElasticLogger.NETFramework.ES.Logging
{
    /// <summary>
    /// 日志缓冲区，用于在Elasticsearch不可用时临时存储日志
    /// </summary>
    internal class LogBuffer
    {
        private readonly ConcurrentQueue<ElasticLogEntry> _buffer;
        private readonly int _maxBufferSize;
        private readonly object _lockObject = new object();

        /// <summary>
        /// 初始化 LogBuffer 类的新实例
        /// </summary>
        /// <param name="maxBufferSize">缓冲区最大大小</param>
        public LogBuffer(int maxBufferSize = 1000)
        {
            _buffer = new ConcurrentQueue<ElasticLogEntry>();
            _maxBufferSize = maxBufferSize;
        }

        /// <summary>
        /// 将日志条目添加到缓冲区
        /// </summary>
        /// <param name="logEntry">日志条目</param>
        /// <returns>是否成功添加</returns>
        public bool Enqueue(ElasticLogEntry logEntry)
        {
            if (logEntry == null)
                return false;

            // 如果缓冲区已满，移除最旧的日志条目
            if (_buffer.Count >= _maxBufferSize)
            {
                _buffer.TryDequeue(out _);
            }

            _buffer.Enqueue(logEntry);
            return true;
        }

        /// <summary>
        /// 从缓冲区中取出指定数量的日志条目
        /// </summary>
        /// <param name="count">要取出的日志条目数量</param>
        /// <returns>日志条目列表</returns>
        public List<ElasticLogEntry> Dequeue(int count)
        {
            var result = new List<ElasticLogEntry>();

            for (int i = 0; i < count && _buffer.TryDequeue(out var item); i++)
            {
                result.Add(item);
            }

            return result;
        }

        /// <summary>
        /// 获取缓冲区中的日志条目数量
        /// </summary>
        public int Count => _buffer.Count;
    }
}